
#include"../log/log.h"

enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY,
};
class RollBytimesink : public logs::sink
{
public:
        RollBytimesink(const std::string& basename,TimeGap gap_size)
        :_basename(basename)
        ,_filename(basename)
        {
            switch (gap_size)
            {
                case TimeGap::GAP_SECOND: _gap_size = 1;break;
                case TimeGap::GAP_MINUTE: _gap_size = 60;break;
                case TimeGap::GAP_HOUR: _gap_size = 3600;break;
                case TimeGap::GAP_DAY: _gap_size = 3600*24;break;
            }
            _old_time =  logs::util::Date::now();
            _cur_gap = logs::util::Date::now() % _gap_size;
            CreateNewfile();//构建文件名
            logs::util::file::CreateDreactor(logs::util::file::pathname(_filename));//创建文件
            _ofs.open(_filename , std::ofstream::binary | std::ofstream::app);
            assert(_ofs.is_open());
        }
        void log(const char* dst,size_t size)override
        {
            if(logs::util::Date::now() >= _old_time + _gap_size)
            {
                _old_time += _gap_size;
                _ofs.close();
                CreateNewfile();
                _ofs.open(_filename,std::ofstream::binary | std::ofstream::app); 
                assert(_ofs.is_open());
            }
            //打开并写入
            _ofs.write(dst,size);
            assert(_ofs.good());
        }
        void CreateNewfile()
        {
            std::stringstream sst;
            sst<< _basename;
            struct tm st;
            const time_t t = time(nullptr);
            localtime_r(&t,&st);
            sst<< st.tm_year+1900;
            sst<< st.tm_mon+1;
            sst<< st.tm_mday;
            sst<<st.tm_hour;
            sst<<st.tm_min;
            sst<<st.tm_sec;
            _filename = sst.str();
        }
        std::ofstream _ofs;
        std::string _filename;
        std::string _basename;
        int _old_time;
        int _cur_gap;//当前时间段
        int _gap_size;//切换时间间隔
};
void test5()//测试日志落地拓展功能
{
    logs::LogMsg msg(logs::loglevel::level::DEBUG,__FILE__,"日志器1","测试日志",__LINE__);
    logs::Formater ft;
    std::string ret = ft.format(msg);//此时是把消息准备好了
    //下面是解决消息的输出方向
   auto sptr3 = logs::Factorysink::Create<RollBytimesink>("./test/test.log", TimeGap::GAP_SECOND);
   auto i = logs::util::Date::now();
   while(i + 5 > logs::util::Date::now())//往文件输出日志五秒,应该创建五个文件
   {
        sptr3->log(ret.c_str(),ret.size());
        usleep(10000);
   }
}

int main()
{
    test5();
    
    return 0;
}